<template>
  <div class="activity" v-infinite-scroll="getLog" infinite-scroll-disabled="loading" infinite-scroll-distance="300">
    <!-- 按钮组 -->
    <div style="display: flex; align-items: center">
      <button class="btn" :class="disabledContent ? '' : 'is-select'" @click="handleClick('1')">
        <i class="wk wk-add"></i>
        <span style="margin-left: 5px">写跟进</span>
      </button>

      <button class="btn" :class="disabledContent ? '' : 'is-select'" @click="addRecord('contacts')">
        <i class="wk wk-add"></i>
        <span style="margin-left: 5px">创建联系人</span>
      </button>

      <button class="btn" :class="disabledContent ? '' : 'is-select'" @click="addRecord('business')">
        <i class="wk wk-add"></i>
        <span style="margin-left: 5px">创建商机</span>
      </button>

      <button class="btn" :class="disabledContent ? '' : 'is-select'" @click="addRecord('contract')">
        <i class="wk wk-add"></i>
        <span style="margin-left: 5px">创建合同</span>
      </button>

      <button class="btn" :class="disabledContent ? '' : 'is-select'" @click="addRecord('receivables')">
        <i class="wk wk-add"></i>
        <span style="margin-left: 5px">创建回款</span>
      </button>
    </div>

    <!-- 日志 -->
    <div class="mix-content">
      <div
        style="display: flex; align-items: center; padding: 0px 10px"
        v-if="disabledContent"
        @click="
          disabledContent = !disabledContent
          activityData.activityTypeId = 'lucy'
        "
      >
        <i class="wk wk-write" style="color: #e6e6e6; font-size: 15px"></i>
        <a-input disabled style="border: 0" />
      </div>
      <div v-else>
        <div class="" style="padding: 8px">
          <div class="top">
            <a-select v-model="activityData.category" style="width: 120px" @change="handleChange">
              <a-select-option value="打电话">打电话</a-select-option>
              <a-select-option value="发邮件">发邮件</a-select-option>
              <a-select-option value="发短信">发短信</a-select-option>
              <a-select-option value="见面拜访">见面拜访</a-select-option>
              <a-select-option value="活动">活动</a-select-option>
            </a-select>

            <a-date-picker
              v-model="activityData.nextTime"
              style="margin-left: 10px"
              format="YYYY-MM-DD HH:mm:ss"
              :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              @change="onChange"
            />
            <i class="close wk wk-close" @click="clearContent"></i>
          </div>
          <div style="margin-top: 10px">
            <textarea
              v-model="activityData.content"
              :autoSize="false"
              style="width: 100%; border: none; height: 80px"
              @input="changeInput"
            ></textarea>
          </div>
          <div class="bottom">
            <!-- <div class="upload" @click="barClick('img')">
              <i class="wk wk-picture"></i>
              <span>图片</span>
            </div>
            <div class="upload" @click="barClick('file')">
              <i class="wk wk-file"></i>
              <span>附件</span>
            </div> -->
            <div style="margin-left: auto; cursor: pointer">
              <a-button @click="sendLog" :loading="sendLoading" type="primary">发布</a-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 附件 -->
      <input ref="fileInput" accept="*.*" type="file" class="file-input" multiple @change="uploadFile" />
      <input ref="imgInput" accept="image/*" type="file" class="file-input" multiple @change="uploadFile" />
    </div>

    <!-- 搜索功能 -->
    <div style="margin-top: 20px; display: flex; align-items: center; justify-content: flex-end">
      <a-input
        ref="userNameInput"
        placeholder="关键字搜索"
        style="width: 200px"
        v-model="filterValue.search"
        @keyup.enter="refreshLogList(true)"
      >
        <a-icon slot="prefix" type="search"
      /></a-input>
      <a-select :default-value="timeOptions[0].value" style="width: 200px; margin-left: 10px" @change="timeTypeChange">
        <a-select-option v-for="(timeLine, index) in timeOptions" :key="index" :value="timeLine.value">{{
          timeLine.label
        }}</a-select-option>
      </a-select>
    </div>

    <!-- logs -->
    <div class="log-section" v-for="(seciton, secitonIndex) in logList" :key="secitonIndex">
      <div class="log-section__title">
        <span class="section-title">
          <span class="section-title__time">{{ seciton.time }}</span>
        </span>
      </div>
      <div class="log-section__content" v-for="(item, index) in seciton.list" :key="index">
        <div class="img">
          <i class="wk wk-message log-cell__mark"></i>
        </div>
        <div class="content">
          <div style="display: flex; align-items: center">
            <div class="taskBottom">{{ item.ownerUserId_dictText.substring(0, 1) }}</div>
            <div>
              <div style="font-size: 13px; color: #333">{{ item.ownerUserId_dictText }}</div>
              <div style="font-size: 12px; color: #999; margin-top: 3px" v-if="item.nextTime">
              {{ item.nextTime }}
              </div>
              <div style="font-size: 12px; color: #999; margin-top: 3px" v-else>
              {{ item.createTime }}
              </div>
            </div>
            <a-tag color="pink" style="margin-left: 25px">
              {{ item.category }}
            </a-tag>
            <div class="detail-container-header-top-right">
              <a><span class="wk wk-leads"></span></a>客户-跟进记录
              <a-dropdown :trigger="['click']">
                <a-button type="default" icon="ellipsis" />
                <a-menu slot="overlay">
                  <!-- <a-menu-item>
                    <a @click="changeLeadsToCustomer">
                      <span class="icon wk wk-transform"></span>
                      修改</a
                    >
                  </a-menu-item> -->
                  <a-menu-item>
                    <a @click="deleteLog(item.activityId)"> <span class="icon wk wk-delete"></span>删除</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </div>
          </div>
          <div style="margin-top: 10px">
            {{ item.content }}
          </div>
        </div>
      </div>
    </div>

    <p v-if="loading" class="scroll-bottom-tips">加载中...</p>
    <p v-if="noMore" class="scroll-bottom-tips" style="text-align: center; font-size: 12px; color: #666">没有更多了</p>

    <crm-contract-modal ref="contract" :customerId="postParams.customerId"></crm-contract-modal>
    <crm-contacts-modal ref="contacts" :customerId="postParams.customerId"></crm-contacts-modal>
    <crm-business-modal ref="business" :customerId="postParams.customerId"></crm-business-modal>
    <crm-receivables-modal ref="receivables" :customerId="postParams.customerId"></crm-receivables-modal>
  </div>
</template>

<script>
import CrmContactsModal from '@/views/crm/contacts/modules/CrmContactsModal.vue'
import CrmContractModal from '@/views/crm/contract/modules/CrmContractModal.vue'
import CrmBusinessModal from '@/views/crm/business/modules/CrmBusinessModal.vue'
import CrmReceivablesModal from '@/views/crm/receivables/modules/CrmReceivablesModal.vue'
import { httpAction } from '@/api/manage'
import moment from 'moment'
import { mapGetters } from 'vuex'
import { getAction } from '@/api/manage'
import debounce from 'lodash/debounce'
export default {
  name: 'RelativeRemark',
  props: {
    id: String,
  },
  model: {
    event: 'change',
  },
  components: {
    CrmContactsModal,
    CrmContractModal,
    CrmBusinessModal,
    CrmReceivablesModal,
  },
  data() {
    return {
      activityType: 'customer',
      loading: false,
      page: 1,
      noMore: false,
      sendLoading: false,
      disabledContent: true, //根据是否输入
      showRelativeType: '' /** 展示关联弹窗 */,
      // scrollKey: Date.now(),
      // 筛选
      isSearchRequest: false,
      filterValue: {},
      timeOptions: [
        { label: '全部', value: '' },
        { label: '最近1天', value: '1' },
        { label: '最近7天', value: '7' },
        { label: '最近30天', value: '30' },
        { label: '最近60天', value: '60' },
      ],
      activityData: {
        batchId: '',
        type: '',
        activityTypeId: '',
        category: '打电话',
        content: '',
        files: '',
        images: '',
        business: '',
        contactsId: '',
        followType: '',
        nextTime: '',
      },
      logList: [],
      postParams: {
        customerId: '',
      },
      url: {
        list: '/online/api/pagingCrmActivity',
        create: '/online/api/createCrmActivity',
        delete: '/online/api/deleteCrmActivity',
      },
    }
  },
  watch: {
    id(val) {
      this.postParams.customerId = val
      this.refreshLogList()
    },
  },
  created() {
    //this.refreshLogList()
  },
  methods: {
    moment,
    // 活动类型
    handleClick(type) {
      this.disabledContent = !this.disabledContent
      this.activityData.type = type
    },

    // 清空输入框
    clearContent() {
      this.activityData.content = ''
    },

    // 输入框
    changeInput(e) {
      this.$emit('change', e.target.value)
    },

    // 下拉选择器
    handleChange(e) {
      console.log('跟进下拉', e)
    },
    // 时间选择器
    onChange(date, dateString) {
      this.activityData.nextTime = dateString
      console.log(date, dateString)
    },

    // 上传图片
    barClick(type) {
      this.showRelativeType = type
      if (type == 'file') {
        this.$refs.fileInput.click()
      } else if (type == 'img') {
        this.$refs.imgInput.click()
      }
    },
    /**
     * 图片选择出发
     */
    uploadFile(event) {
      var files = event.target.files
      if (files.length) {
        for (let index = 0; index < files.length; index++) {
          const file = files[index]
          if (file.type.indexOf('image') == -1 && this.showRelativeType == 'img') {
            this.$message.error('请上传正确的文件类型')
            return
          }
        }
        var type = event.target.accept == 'image/*' ? 'img' : 'file'

        for (let index = 0; index < files.length; index++) {
          const file = files[index]
          this.$emit('successFile', { file, type })
          // this.uploadFileRequest(file, type)
        }
        event.target.value = ''
      }
    },
    /**
     * 文件上传
     */
    uploadFileRequest(file, type, result) {
      // 请求接口
      console.log('请求接口')
      // this.$uploadFile.upload({
      //   file: file,
      //   params: {
      //     type: type,
      //     batchId: this.batchId
      //   }
      // }).then(({ res }) => {
      //   const data = res.data || {}
      //   data.size = fileSize(file.size)
      //   if (type == 'img') {
      //     this.imgFiles.push(data)
      //   } else {
      //     data['icon'] = getFileTypeIcon(file)
      //     this.files.push(data)
      //   }
      //   if (result) {
      //     result()
      //   }
      // }).catch(() => {})
    },

    /**
     * 获取日志
     */
    getLog() {
    if(this.id ==null)return;
      const params = {
        batchId: this.id,
        page: this.page,
        activityType: this.activityType,
        // activityTypeId: this.id,
      }
      if (this.filterValue.search) {
        params.search = this.filterValue.search
      }
      if (this.filterValue.timeLine) {
        params.intervalDay = this.filterValue.timeLine || ''
      }
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.loading = false
          if (!this.noMore) {
            this.page++

            if (this.logList.length) {
              const lastLog = this.logList[this.logList.length - 1]
              if (res.result.time && res.result.list.length && lastLog.time != res.result.time) {
                this.logList.push(res.result)
              }
            } else {
              if (res.result.time && res.result.list.length) {
                this.logList.push(res.result)
              }
            }
          }
          this.noMore = res.result.lastPage
        }
      })
    },
    deleteLog(id) {
      const that = this
      this.$confirm({
        title: '提示',
        content: '您确定要删除吗？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          httpAction(that.url.delete, { activityId: id }, 'delete')
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.refreshLogList()
                that.getLog()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        },
        onCancel() {},
      })
    },
    ...mapGetters(['name']),

    /**
     * 初始化日志
     */
    refreshLogList(isSearchRequest) {
      this.isSearchRequest = isSearchRequest || false
      this.page = 1
      this.noMore = false
      this.logList = []
      // this.scrollKey = Date.now()
      this.getLog()
    },
    /**
     * 发布日志
     */
    sendLog() {
      if (!this.activityData.content) {
        this.$message.error('请输入跟进内容')
        return
      }
      const params = {}
      params.batchId = this.id
      params.type = this.activityData.type
      params.activityType = this.activityType
      params.activityTypeId = this.id
      params.category = this.activityData.category
      params.content = this.activityData.content
      params.activityTypeId = this.activityData.activityTypeId
      params.createUserId_dictText = this.name()
      params.nextTime = this.activityData.nextTime || ''
      params.isEvent = 0
      this.sendLoading = true

      httpAction(this.url.create, params, 'post')
        .then((res) => {
          this.sendLoading = false
          this.$message.success('发布成功')
          this.refreshLogList()
        })
        .finally(() => {
          this.sendLoading = false
          this.getLog()
          this.activityData.content = ''
          this.activityData.category = ''
          this.activityData.nextTime = ''
        })
    },
    /**
     * 时间筛选
     */
    timeTypeChange(data) {
      this.filterValue.timeLine = data
      this.refreshLogList()
    },
    addRecord(type) {
      setTimeout(() => {
        this.$refs[type].add()
      }, 300)
    },
  },
}
</script>

<style lang="less" scoped>
input,
button,
select,
textarea {
  outline: none;
  border: 0;
}
// Activity样式
.activity {
  .btn {
    display: flex;
    align-items: center;
    border: 0;
    outline: none;
    background-color: #f1f5fd;
    margin-right: 10px;
    margin-bottom: 5px;
    cursor: pointer;
    padding: 2px 8px;
    border-radius: 5px;
    &:hover {
      background: #168a40;
      border-color: #168a40;
      color: #fff;
    }
  }
  .is-select {
    background: #168a40;
    border-color: #168a40;
    color: #fff;
  }
  .mix-content {
    margin-top: 15px;
    position: relative;
    border: 1px solid #e6e6e6;
    border-radius: 3px;
    background-color: #fff;
    .close {
      margin-left: auto;
      color: #d9d9d9;
      &:hover {
        color: #168a40;
      }
    }
    .top {
      display: flex;
      align-items: center;
    }
    .bottom {
      display: flex;
      align-items: center;
      /deep/ .ant-btn {
        margin-right: 0px;
        margin-bottom: 0px;
      }
      .upload {
        display: flex;
        align-items: center;
        color: #666;
        font-size: 12px;
        margin-right: 15px;
        span {
          margin-left: 5px;
        }
        &:hover {
          color: #168a40;
        }
      }
    }
  }
  .mix-content:hover {
    cursor: pointer;
    border-color: #c0c4cc;
  }
  .file-input {
    display: none;
  }

  .log-section {
    margin-top: 20px;
    &:nth-last-child(1) {
      &::before {
        top: 50px;
      }
    }
    .log-section__title {
      padding: 8px 0;
      .section-title {
        background-color: #f1f5fd;
        color: #fff;
        font-size: 12px;
        padding: 4px 10px;
        height: 20px;
        border-radius: 15px;
      }
      .section-title__time {
        color: #666;
        font-weight: 600;
      }
      .section-title__time:before {
        content: ' ';
        position: relative;
        width: 6px;
        height: 6px;
        border-radius: 3px;
        background-color: #666;
        margin-right: 5px;
        bottom: 2px;
        display: inline-block;
      }
    }
    .log-section__content {
      font-size: 12px;
      padding: 10px 15px;
      display: flex;
      align-items: flex-start;
      position: relative;
      &::before {
        position: absolute;
        content: ' ';
        width: 1px;
        top: 0;
        left: 34px;
        bottom: 0;
        background-color: #e6e6e6;
      }
      &:nth-child(2) {
        &::before {
          top: 24px;
        }
      }
      &:nth-last-child(1) {
        &::before {
          height: 40px;
        }
      }

      .img {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        .log-cell__mark {
          left: -10px;
          top: 24px;
          background-color: #487dff;
          color: #fff;
          border-radius: 4px;
          padding: 4px 6px;
          font-size: 12px;
          z-index: 1;
        }
      }
      .taskBottom {
        width: 35px;
        height: 35px;
        border-radius: 50%;
        font-size: 12px;
        background-color: rgb(35, 98, 251);
        color: #ffffff;
        border: 1px solid #e6e6e6;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
      }
      .detail-container-header-top-right {
        position: absolute;
        right: 0;
        top: 0;
      }
    }
  }
}
</style>
